/*
@hehung
2023-2-8
转载请注明出处，版权由@hehung所有
email: 1398660197@qq.com
wechat: hehung95
*/

#include "hal_data.h"
#include "app_uart.h"

#include <string.h>


#define UART_PRINTF_ENABLE           (0U)
#define UART_SCANF_ENABLE            (0U)

#if ((UART_PRINTF_ENABLE == 1U) || (UART_SCANF_ENABLE == 1U))
#include <stdio.h>
#endif


/* variables for uart9 - used for printf */
static volatile bool uart9_send_complete_flag = false;
volatile s_UartBufType uart_buf;


// Uart initialize
void Uart_Init(void)
{
	fsp_err_t err = FSP_SUCCESS;
	
	/* Open the transfer instance with initial configuration. */
    err = R_SCI_UART_Open(&g_uart9_ctrl, &g_uart9_cfg);
    assert(FSP_SUCCESS == err);
}

// callback function for uart9
void uart9_notification(uart_callback_args_t * p_args)
{
	if (p_args->event == UART_EVENT_TX_COMPLETE)
	{
		uart9_send_complete_flag = true;
	}
	else if (p_args->event == UART_EVENT_RX_CHAR)
	{
		uart_buf.data_buf[uart_buf.data_idx ++] = (char)p_args->data;
	}
}

void Uart_SendData(const char *dataPtr)
{
	uint8_t i;
	uint8_t len = (uint8_t)strlen(dataPtr);

	for (i = 0; i < len; i++)
	{
		(void)R_SCI_UART_Write(&g_uart9_ctrl, (uint8_t *)&dataPtr[i], 1);
		while (uart9_send_complete_flag == false) {}
		uart9_send_complete_flag = false;
	}
}

void Uart_SendHexData(const char *dataPtr, const uint8_t dataLen)
{
	uint8_t i;

	for (i = 0; i < dataLen; i++)
	{
		(void)R_SCI_UART_Write(&g_uart9_ctrl, (uint8_t *)&dataPtr[i], 1);
		while (uart9_send_complete_flag == false) {}
		uart9_send_complete_flag = false;
	}
}

#if (UART_PRINTF_ENABLE == 1U)
// fputs for printf or other print function in standard
int fputc(int ch, FILE *f)
{
	fsp_err_t err = FSP_SUCCESS;
	
	(void)f;
	err = R_SCI_UART_Write(&g_uart9_ctrl, (uint8_t *)&ch, 1);
	if(FSP_SUCCESS != err) 
		__BKPT();
	/* Waiting until transmit finished */
	while(uart9_send_complete_flag == false) 
	{}
	uart9_send_complete_flag = false;
	
    return ch;
}
#endif

#if (UART_SCANF_ENABLE == 1U)
// fgets for scanf or other input function in standard
int fgetc(FILE *f) 
{	
	(void)f;
	
	while (uart9_recv_complete_flag == false)
	{}
	uart9_recv_complete_flag = false;

	return (int)uart9_recv_char;
}
#endif


